<?php
/**
 * Created by PhpStorm.
 * User: keke
 * Date: 2020/8/14
 * Time: 11:35
 */

namespace App\Http\Controllers\Api;

use App\Model\AdminLog;
use App\Model\FinanceRoomPunish;
use App\Model\FinanceRoomSettle;
use App\Model\OperationLogs;
use App\Model\Users;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class SettlementController extends BaseController
{
    protected $roomPunishModel;
    protected $roomSettleModel;
    protected $userModel;

    public function __construct(Request $request, FinanceRoomPunish $financeRoomPunish, FinanceRoomSettle $financeRoomSettle, Users $usersModel)
    {
        parent::__construct($request);
        $this->roomPunishModel = $financeRoomPunish;
        $this->roomSettleModel = $financeRoomSettle;
        $this->userModel = $usersModel;
    }

    public function getRoomPunishList(Request $request)
    {
        $result = $this->roomPunishModel->getRoomPunishList($request);
        if ($result) {
            foreach ($result as $key => &$val) {
                $year = substr($val->month, 0, 4);
                $month = substr($val->month, -2);
                $val->month = $year . '年' . $month . '月';
            }
        }
        return $this->toJson(self::SUCCESS, $result);
    }


    public function createRoomPunished(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'room_id' => 'required',
            'ratio' => 'required|integer|min:1|max:30'
        ], [
            'room_id.required' => '房间Id不可为空',
            'ratio.required' => '惩罚比例值不可为空',
            'ratio.integer' => '惩罚比例值必须为整数',
            'ratio.min' => '惩罚比例最小值为1',
            'ratio.max' => '惩罚比例最大值为30',
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
        }

        $res = $this->roomPunishModel->createRoomPunished($request->only(['room_id', 'ratio']));
        if ($res['code']) {
            return $this->toJson(self::ERROR, [], $res['msg']);
        }
        OperationLogs::createData($request, OperationLogs::FINANCE, '新增房间惩罚', $request->input('room_id'));
        return $this->toJson(self::SUCCESS);
    }


    public function deleteRoomPunished(Request $request, $id)
    {
        $res = $this->roomPunishModel->deleteRoomPunished(['id' => $id]);
        if ($res['code'] !== 0) {
            return $this->toJson(self::ERROR, [], $res['msg']);
        }
        OperationLogs::createData($request, OperationLogs::FINANCE, '删除房间惩罚', $id);
        return $this->toJson(self::SUCCESS);
    }


    public function getRoomSettleList(Request $request)
    {
        $result = $this->roomSettleModel->getRoomSettleList($request);
        $result = json_decode(json_encode($result), true);
        if ($result['data']) {
            $userId = array_unique(array_column($result['data'], 'to_user_id'));
            $userInfo = $this->userModel->getUserInfoByIds($userId);
            $userUid = array_column($userInfo, 'uuid', 'user_id');
            $userNickname = array_column($userInfo, 'nickname', 'user_id');
            foreach ($result['data'] as $key => $val) {
                $year = substr($val['month'], 0, 4);
                $month = substr($val['month'], -2);
                $result['data'][$key]['month'] = $year . '年' . $month . '月';
                if (isset($userUid[$val['to_user_id']])) {
                    $result['data'][$key]['user_uid'] = $userUid[$val['to_user_id']];
                }
                if (isset($userNickname[$val['to_user_id']])) {
                    $result['data'][$key]['nickname'] = $userNickname[$val['to_user_id']];
                }
            }
        }
        return $this->toJson(self::SUCCESS, $result);
    }


    public function roomSettleApproved(Request $request, $id)
    {
        $type = $request->input('type') ?? 0;

        $res = $this->roomSettleModel->roomSettleApproved(['settleId' => $id, 'type' => intval($type)]);
        if ($res['code'] !== 0) {
            return $this->toJson(self::ERROR, [], $res['msg']);
        }
        if (intval($type)) {
            OperationLogs::createData($request, OperationLogs::FINANCE, '同意结算房间钻石', $id);
        } else {
            OperationLogs::createData($request, OperationLogs::FINANCE, '同意房间预支', $id);
        }
        return $this->toJson(self::SUCCESS);
    }


    public function roomSettleApprovedAll(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required'
        ], [
            'id.required' => '预支ID不能为空'
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
        }

        $settleIds = $request->input('id');
        $settleIds = implode(',', $settleIds);
        $res = $this->roomSettleModel->roomSettleApprovedAll(['settleId' => $settleIds]);
        if ($res['code'] !== 0) {
            return $this->toJson(self::ERROR, [], $res['msg']);
        }
        OperationLogs::createData($request, OperationLogs::FINANCE, '同意房间预支', $settleIds);
        return $this->toJson(self::SUCCESS);
    }


    public function roomSettleReject(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required',
            'reject_desc' => 'required|max:200'
        ], [
            'id.required' => '预支ID不能为空',
            'reject_desc.required' => '驳回描述不可为空',
            'reject_desc.max' => '驳回描述不可超过200个字符'
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
        }

        $data = [
            'desc' => $request->input('reject_desc'),
            'settleId' => $request->input('id')
        ];
        $res = $this->roomSettleModel->roomSettleReject($data);
        if ($res['code']) {
            return $this->toJson(self::ERROR, [], $res['msg']);
        }
        OperationLogs::createData($request, OperationLogs::FINANCE, '驳回房间预支',$request->input('id'));
        return $this->toJson(self::SUCCESS);
    }



    public function roomSettleFreeze(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required',
        ], [
            'id.required' => '预支ID不能为空',
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
        }

        $data = [
            'settleId' => $request->input('id')
        ];
        $res = $this->roomSettleModel->roomSettleFreeze($data);
        if ($res['code']) {
            return $this->toJson(self::ERROR, [], $res['msg']);
        }
        OperationLogs::createData($request, OperationLogs::FINANCE, '驳回房间冻结', $request->input('id'));
        return $this->toJson(self::SUCCESS);
    }

    public function roomSettleUnfreeze(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required',
        ], [
            'id.required' => '预支ID不能为空',
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
        }

        $data = [
            'settleId' => $request->input('id')
        ];
        $res = $this->roomSettleModel->roomSettleunfreeze($data);
        if ($res['code']) {
            return $this->toJson(self::ERROR, [], $res['msg']);
        }
        OperationLogs::createData($request, OperationLogs::FINANCE, '驳回房间冻结', $request->input('id'));
        return $this->toJson(self::SUCCESS);
    }

    public function setFinalDiamond(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required',
            'final_diamond' => 'required|integer'
        ], [
            'id.required' => 'ID不能为空',
            'final_diamond.required' => '钻石数不可为空',
            'final_diamond.integer' => '钻石数必须是整数'
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
        }

        $finalDiamond = $request->input('final_diamond');
        $totalDiamond = $request->input('diamond');
        if (intval($finalDiamond) > intval($totalDiamond)) {
            return $this->toJson(self::ERROR, [], '钻石数修改超限');
        }

        $data = [
            'diamond' => $request->input('final_diamond'),
            'settleId' => $request->input('id')
        ];
        $res = $this->roomSettleModel->setFinalDiamond($data);
        if ($res['code']) {
            return $this->toJson(self::ERROR, [], $res['msg']);
        }
        OperationLogs::createData($request, OperationLogs::FINANCE, '修改房间可预支钻石数', $request->input('id'));
        return $this->toJson(self::SUCCESS);
    }


    public function setRejectDesc(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required',
            'desc' => 'required|max:200'
        ], [
            'id.required' => 'ID不能为空',
            'desc.required' => '描述不可为空',
            'desc.max' => '描述不可超过200个字符'
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
        }

        $data = [
            'desc' => $request->input('desc'),
            'settleId' => $request->input('id')
        ];
        $res = $this->roomSettleModel->setRejectDesc($data);
        if ($res['code']) {
            return $this->toJson(self::ERROR, [], $res['msg']);
        }
        OperationLogs::createData($request, OperationLogs::FINANCE, '修改预支/结算描述', $request->input('id'));
        return $this->toJson(self::SUCCESS);
    }


    public function getRoomSettlementList(Request $request)
    {
        $result = $this->roomSettleModel->getRoomSettlementList($request);
        if ($result) {
            foreach ($result as $key => &$val) {
                $year = substr($val->month, 0, 4);
                $month = substr($val->month, -2);
                $val->month = $year . '年' . $month . '月';
                if (intval($val->new_status) > 0) {
                    $val->new_status = 1;
                } else {
                    $val->new_status = 0;
                }
            }
        }
        return $this->toJson(self::SUCCESS, $result);
    }


    public function createNewsList(Request $request)
    {
        $res = $this->roomSettleModel->createNewsList();
        if ($res['code']) {
            return $this->toJson(self::ERROR, [], '上月已结算');
        }
        OperationLogs::createData($request, OperationLogs::FINANCE, '生成房间结算列表');
        return $this->toJson(self::SUCCESS);
    }


    public function getRoomSettleDetail(Request $request, $month)
    {
        if (empty($month)) {
            return $this->toJson(self::PARAM_ERROR, [], '查询日期不能为空');
        }
        $month = str_replace('月', '', str_replace('年', '', $month));
        $result = $this->roomSettleModel->getRoomSettleDetail($request, intval($month));
        $result = json_decode(json_encode($result), true);
        if ($result['data']) {
            $userId = array_unique(array_column($result['data'], 'to_user_id'));
            $userInfo = $this->userModel->getUserInfoByIds($userId);
            $userUid = array_column($userInfo, 'uuid', 'user_id');
            $userNickname = array_column($userInfo, 'nickname', 'user_id');
            foreach ($result['data'] as $key => $val) {
                $year = substr($val['month'], 0, 4);
                $month = substr($val['month'], -2);
                $result['data'][$key]['month'] = $year . '年' . $month . '月';
                if (isset($userUid[$val['to_user_id']])) {
                    $result['data'][$key]['user_uid'] = $userUid[$val['to_user_id']];
                }
                if (isset($userNickname[$val['to_user_id']])) {
                    $result['data'][$key]['nickname'] = $userNickname[$val['to_user_id']];
                }
            }
        }
        return $this->toJson(self::SUCCESS, $result);
    }


    public function settleThisMonth(Request $request, $month)
    {
        if (empty($month)) {
            return $this->toJson(self::PARAM_ERROR, [], '日期不能为空');
        }
        $month = str_replace('月', '', str_replace('年', '', $month));
        $lastMonth = date('Ym', strtotime("-1 month"));
        if ($month != $lastMonth) {
            return $this->toJson(self::ERROR, [], '不允许操作');
        }
        $res = $this->roomSettleModel->settleThisMonth();
        if ($res['code']) {
            return $this->toJson(self::ERROR, [], $res['msg']);
        }
        OperationLogs::createData($request, OperationLogs::FINANCE, '结算房间钻石', $month);
        return $this->toJson(self::SUCCESS);
    }
}
